#-*- coding: utf-8 -*-
from config import MainConfig
from requires import check_requires
import pmloader, services, events
import __builtin__
import sys


# System core.
class PMCore():
    comdir = "components"           # components directory
    #modules = []                   # modules list
    #comlist = {}                   # components dictionary
    global_dictionary = {}          # global dictionary for the interaction between the components
    global_config = MainConfig()    # config reader/writer
    evts = events.Events()
    def __init__(self):
        # Read the config file
        self.global_config.read("config")
        # Read the components directory and create the list of the 
        # modules and the components dictionary.
        self.global_dictionary["components directory"] = self.comdir
        self.comlist = pmloader.load_components(self.comdir,"restrict.lst")
        
        # Analyze enabled components config
        enabled_lst = [(x,y) for x,y in self.global_config.get_module_options("Enabled components").items()]
        chconf = False
        for n,o in self.comlist.items():
            if o.name.lower() not in [x for x,y in enabled_lst]:
                chconf = True
                self.global_config.set("Enabled components",o.name,"true")
        if chconf:
            self.global_config.write(open("config","w"))
            enabled_lst = [(x,y) for x,y in self.global_config.get_module_options("Enabled components").items()]
                
        enabled_lst = filter(lambda x: x[1].lower() == "true",enabled_lst)
        enabled_lst = [x for x,y in enabled_lst]
        
        # Remove disabled components
        for n,o in self.comlist.items():
            if o.name.lower() not in enabled_lst:
                print "\nDISABLED: " + o.name
                del self.comlist[n]
        
        # Check dependings
        chagain = True
        while chagain:
            chagain = False
            # Generate service list
            self.services = services.Services(self.comlist)
            self.builtin_services()
            if self.services.errors:
                print "\n"
                for e in self.services.errors:
                    print "ERROR: conflict services:", e
                sys.exit()
            # Check requires
            for n,o in self.comlist.items():
                err_lst = []
                if not check_requires(self.services.svclst, o.requires, errors = err_lst):
                    print "ERROR:", o.name, ": not satisfied depending: ", " ".join(err_lst)
                    print o.name, "disble"
                    del self.comlist[n]
                    chagain = True
        
        __builtin__.get_service = self.services.get
        __builtin__.add_listener = self.evts.add_listener
        __builtin__.remove_listener = self.evts.remove_listener
        __builtin__.send_event = self.evts.send_event
        
        # Order component list by weight.
        ordered_cl = [(x.name,x.weight) for x in self.comlist.values()]
        ordered_cl.sort(key = lambda x:x[1])

        # Transmit the config into the componets.
        for c,v in ordered_cl:
            com = self.comlist[c]
            print "\nDONE: component: " + com.name
            if com.provides:
                print "provide: " + " ".join([x["name"] + ";" for x in com.provides])
            print "version: " + com.version
            print "author: " + com.author
            com.set_start_settings(self.global_config.get_module_options(com.name))
                                        
        # Before DirectImport initialization
        for c,v in ordered_cl:
            com = self.comlist[c]
            com.before_direct_import()

        from direct.directbase import DirectStart
        
        # After DirectImport initialization
        for c,v in ordered_cl:
            com = self.comlist[c]
            com.after_direct_import()

    def builtin_services(self):
        pass
